package com.algorithm;

/**
 * 寻找旋转排序数组中的最小值
 */
public class FindMinimumInRotatedSortedArray {


    public static int findMin(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        int left = 0;
        int right = nums.length - 1;
        if (nums[right]>nums[left]){
            return nums[0];
        }
        return searchTemp(left, right, nums);
    }

    public static void main(String[] args) {
//        int[] arr = new int[]{4, 5, 6, 7, 0, 1, 2,3};
        int[] arr = new int[]{2,1};
        int search = findMin(arr);
        System.out.println(search);
    }

    public static int searchTemp(int left, int right, int[] arr) {
        int index = (left + right) / 2;
        //注意：这个判断一定要在前面  不然回数组越界
        if (arr[index] > arr[index + 1]) {
            return arr[index + 1];
        }

        if (arr[index] < arr[index - 1]) {
            return arr[index];
        }

        if (arr[left] < arr[index]) {
            left = index + 1;
        } else {
            right = index - 1;
        }
        return searchTemp(left, right, arr);
    }
}
